const express = require('express');
const router = express.Router();
const rolePermissionService = require('../../services/rolePermissionService');
const adminAuth = require('../../middleware/adminAuth');
const { checkPermission } = require('../../middleware/permission');

/**
 * 获取权限列表
 */
router.get('/', adminAuth, checkPermission('permission', 'read'), async (req, res) => {
  try {
    const {
      page = 1,
      limit = 50,
      search,
      category,
      resource,
      status,
      tree = false
    } = req.query;

    const result = await rolePermissionService.getPermissionList({
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      category,
      resource,
      status,
      tree: tree === 'true'
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取权限列表失败',
      error: error.message
    });
  }
});

/**
 * 获取所有权限（不分页，用于角色分配）
 */
router.get('/all', adminAuth, async (req, res) => {
  try {
    const result = await rolePermissionService.getPermissionList({
      page: 1,
      limit: 1000,
      status: 'active',
      tree: true
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取权限列表失败',
      error: error.message
    });
  }
});

/**
 * 获取权限详情
 */
router.get('/:id', adminAuth, checkPermission('permission', 'read'), async (req, res) => {
  try {
    const permissionId = parseInt(req.params.id);
    const permission = await rolePermissionService.getPermissionById(permissionId);

    res.json({
      success: true,
      data: permission
    });
  } catch (error) {
    res.status(404).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 创建权限
 */
router.post('/', adminAuth, checkPermission('permission', 'create'), async (req, res) => {
  try {
    const { name, displayName, description, resource, action, category, parentId, level } = req.body;

    if (!name || !displayName || !resource || !action) {
      return res.status(400).json({
        success: false,
        message: '权限名称、显示名称、资源和操作不能为空'
      });
    }

    const permission = await rolePermissionService.createPermission({
      name,
      displayName,
      description,
      resource,
      action,
      category,
      parentId,
      level
    });

    res.status(201).json({
      success: true,
      message: '权限创建成功',
      data: permission
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 更新权限
 */
router.put('/:id', adminAuth, checkPermission('permission', 'update'), async (req, res) => {
  try {
    const permissionId = parseInt(req.params.id);
    const { name, displayName, description, resource, action, category, status } = req.body;

    await rolePermissionService.updatePermission(permissionId, {
      name,
      displayName,
      description,
      resource,
      action,
      category,
      status
    });

    res.json({
      success: true,
      message: '权限更新成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 删除权限
 */
router.delete('/:id', adminAuth, checkPermission('permission', 'delete'), async (req, res) => {
  try {
    const permissionId = parseInt(req.params.id);
    
    await rolePermissionService.deletePermission(permissionId);

    res.json({
      success: true,
      message: '权限删除成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;